package client;

import msgs.*;
import msgs.TTConstants.Actions;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.util.*;
import java.net.*;
import javax.swing.event.*;

/**
 * Main working class when connected to the TigerTalk network
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */

public class TTRunningClient extends Thread {
	/**
	 * Static reference to this jframe
	 */
	protected static JFrame jf;
	
	private JPopupMenu blPopupMenu;
	private JMenuItem popupIM, popupBlock, popupRemove;
	private HashMap<String, Integer> blDataStatus;
	private String[] blData;
	private JList bl, buddies, currentUsers;
	private JMenu file, friends, talk, profile, options;
	private JMenuBar jmb;
	private JCheckBoxMenuItem soundSel;
	private JMenuItem logout, exit, addBuddy, removeBuddy, blockBuddy, unblockBuddy, newChat, joinChat, viewProfile, editProfile;
	private JTextField addBuddyJTF, users, title, additionalUsers;
	private JDialog jdAddBuddy, jdRemoveBuddy, jdBlockBuddy, jdUnblockBuddy, newChatDialog, joinChatDialog, jdViewProfile, jdEditProfile;
	private BLRenderer blrender;
	private Vector<String> currentUsersData;
	
	// By continuing to read the following GUI code, you absolve me of all responsibility should your eyeballs fall out.
	public TTRunningClient(String[] blData) {
		jf = new JFrame();
		
		// update the tray icon.. 
		updateTrayIcon();
		this.blData = blData;
		
		// call an update to the buddy list
		BLMsg bm = new BLMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, TTClient.name);
		bm.setAction(TTConstants.Actions.WANT_BL);
		ServerSender.outQ.add((ClientMsg) bm);
		
		// and to the status table
		QueryMsg qm = new QueryMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, TTClient.name);
		HashMap<String, Integer> h = new HashMap<String, Integer>();
		for (String s : TTClient.blData) {
			h.put(s, 0);
		}
		qm.setAction(TTConstants.Actions.QUERY_GROUP);
		qm.setUserList(h);
		ServerSender.outQ.add((ClientMsg) qm);
		
		String[] s = { "no buddy list!" };
		bl = new JList(s);
		blrender = new BLRenderer();
		bl.setCellRenderer(blrender);
		jf.add(bl);
		
		jmb = new JMenuBar();
		file = new JMenu("File");
		file.setMnemonic('F');
		logout = new JMenuItem("Logout");
		logout.setMnemonic('L');
		exit = new JMenuItem("Exit");
		exit.setMnemonic('x');
		
		friends = new JMenu("People");
		friends.setMnemonic('P');
		addBuddy = new JMenuItem("Add Buddy");
		addBuddy.setMnemonic('a');
		removeBuddy = new JMenuItem("Remove Buddy");
		removeBuddy.setMnemonic('r');
		blockBuddy = new JMenuItem("Block User");
		blockBuddy.setMnemonic('B');
		unblockBuddy = new JMenuItem("Unblock User");
		unblockBuddy.setMnemonic('U');
		
		talk = new JMenu("Talk");
		talk.setMnemonic('T');
		newChat = new JMenuItem("Create new chat");
		newChat.setMnemonic('C');
		joinChat = new JMenuItem("Join existing chat");
		joinChat.setMnemonic('J');
		
		profile = new JMenu("Profiles");
		profile.setMnemonic('r');
		viewProfile = new JMenuItem("View Profile");
		viewProfile.setMnemonic('V');
		editProfile = new JMenuItem("Edit Profile");
		editProfile.setMnemonic('E');
		
		options = new JMenu("Options");
		options.setMnemonic('O');
		soundSel = new JCheckBoxMenuItem("Sound");
		soundSel.setMnemonic('S');
		soundSel.setSelected(true);
		
		file.add(logout);
		file.add(exit);
		jmb.add(file);
		
		friends.add(addBuddy);
		friends.add(removeBuddy);
		friends.add(blockBuddy);
		friends.add(unblockBuddy);
		jmb.add(friends);
		
		talk.add(newChat);
		talk.add(joinChat);
		jmb.add(talk);
		
		profile.add(viewProfile);
		profile.add(editProfile);
		jmb.add(profile);
		
		options.add(soundSel);
		jmb.add(options);
		
		TTClient.miLogout.setEnabled(true);
		TTClient.miLogout.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent ae)
			{
				JOptionPane.showMessageDialog(null, "This is temporarily disabled. Please close the window or click File -> Exit", "Disabled!",  JOptionPane.ERROR_MESSAGE);
			}
		});
		
		blPopupMenu = new JPopupMenu();
		popupIM = new JMenuItem("Send Message");
		popupRemove = new JMenuItem("Remove User");
		popupBlock = new JMenuItem("Block User");
		blPopupMenu.add(popupIM);
		blPopupMenu.add(popupRemove);
		blPopupMenu.add(popupBlock);
		
		soundSel.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent ce) {
				if (soundSel.isSelected()) {
					TTClient.setSoundOk(false);
					//soundSel.setSelected(false);
				}
				else {
					TTClient.setSoundOk(true);
					//soundSel.setSelected(true);
				}
			}
		});
		
		bl.setComponentPopupMenu(blPopupMenu);
		popupIM.addActionListener(new ActionListener() {
			// send a new instant message
			public void actionPerformed(ActionEvent ae) {
				PMMsg pm = new PMMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, bl.getSelectedValue().toString(), null, false);
				pm.setName(TTClient.name);
				pm.setWantsUser(bl.getSelectedValue().toString());
				String s = bl.getSelectedValue().toString();
				pm.setWantsUser(s);
				pm.setAction(Actions.PM_USER);
				ServerSender.outQ.add(pm);
			}
		});
		popupRemove.addActionListener(new ActionListener() {
			//remove the selected user from our buddylist
			public void actionPerformed(ActionEvent ae) {
				ArrayList<String> a = new ArrayList<String>();
				for (String s : TTClient.blData) {
					a.add(s);
				}
				a.remove(bl.getSelectedValue().toString());
				BLMsg b = new BLMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, a);
				b.setAction(Actions.BL_UPDATE);
				ServerSender.outQ.add(b);
			}
		});
		popupBlock.addActionListener(new ActionListener() {
			//block the user from contacting us
			public void actionPerformed(ActionEvent ae) {
				BlockMsg b = new BlockMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, bl.getSelectedValue().toString());
				b.setAction(Actions.BLOCK);
				ServerSender.outQ.add(b);
			}
		});
		
		jf.setJMenuBar(jmb);
		jf.setSize(200, 600);
		jf.setLocationRelativeTo(null);
		jf.setTitle("TigerTalk v1.0");
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		jf.setVisible(true);
		
		exit.addActionListener( new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				logout();
				ServerSender.killServerSender();
				ServerListener.killServerListener();
				MsgParser.killMsgParser();
				PMListener.killPMListener();
				PMSender.killPMSender();
				PMParser.killPMParser();
				System.exit(0);
			}
		});
		
		jf.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				logout();
				ServerSender.killServerSender();
				ServerListener.killServerListener();
				MsgParser.killMsgParser();
				PMListener.killPMListener();
				PMSender.killPMSender();
				PMParser.killPMParser();
				System.exit(0);
			}
		});
		
		// ok, so essentially this isn't working correctly -- server throws eof error when we do this. not sure why yet.
		logout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				// disabling this for now, as it keeps causing the server to barf until we close the client.
				JOptionPane.showMessageDialog(null, "This is temporarily disabled. Please close the window or click File -> Exit", "Disabled!",  JOptionPane.ERROR_MESSAGE);
//				logout();
//				ServerSender.killServerSender();
//				ServerListener.killServerListener();
//				MsgParser.killMsgParser();
//				PMListener.killPMListener();
//				PMSender.killPMSender();
//				PMParser.killPMParser();
//				jf.dispose();
//				new TTClient();
			}
		});
		
		// adds a new buddy to our buddy list
		addBuddy.addActionListener( new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				jdAddBuddy = new JDialog();
				JPanel jp = new JPanel();
				JLabel jl = new JLabel("Username");
				addBuddyJTF = new JTextField(10);
				JButton add = new JButton("Add");
				add.setMnemonic('A');
				
				jp.add(jl);
				jp.add(addBuddyJTF);
				jp.add(add);
				jdAddBuddy.add(jp);
				
				jdAddBuddy.pack();
				jdAddBuddy.setTitle("Add Buddy");
				
				jdAddBuddy.setLocationRelativeTo(null);
				jdAddBuddy.setVisible(true);
				
				add.addActionListener( new ActionListener() {
					public void actionPerformed (ActionEvent ae) {
						if (!(addBuddyJTF.getText().equals("")) && !(addBuddyJTF.getText().equals(TTClient.name))) {
							ArrayList<String> a = new ArrayList<String>();
							// throw our current buddy list into a new array
							for (String s : TTClient.blData) {
								if (!(s.equals(""))) {
									a.add(s);
								}
							}
							// add our buddy to the array
							a.add(addBuddyJTF.getText());
							// and request that the server use the new list
							BLMsg b = new BLMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, a);
							b.setAction(Actions.BL_UPDATE);
							b.setName(TTClient.name);
							b.setClientKey(TTClient.key);
							ServerSender.outQ.add(b);
							jdAddBuddy.dispose();
						}
					}
				});
				
				
 				
			}
		});
		
		// converse of above -- remove a buddy from our list
		removeBuddy.addActionListener( new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				jdRemoveBuddy = new JDialog();
				JPanel jp = new JPanel();
				JLabel jl = new JLabel("Username");
				addBuddyJTF = new JTextField(10);
				JButton add = new JButton("Remove");
				add.setMnemonic('R');
				
				jp.add(jl);
				jp.add(addBuddyJTF);
				jp.add(add);
				jdRemoveBuddy.add(jp);
				
				jdRemoveBuddy.pack();
				jdRemoveBuddy.setTitle("Remove Buddy");
				
				jdRemoveBuddy.setLocationRelativeTo(null);
				jdRemoveBuddy.setVisible(true);
				
				add.addActionListener( new ActionListener() {
					public void actionPerformed (ActionEvent ae) {
						if (!(addBuddyJTF.getText().equals(""))) {
							ArrayList<String> a = new ArrayList<String>();
							//copy our current list into an array
							for (String s : TTClient.blData) {
								a.add(s);
							}
							// pull out the requested buddy
							//shockingly this causes no problems if they're not actually on our list... :-) yay!
							a.remove(addBuddyJTF.getText());
							BLMsg b = new BLMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, a);
							// and request that the server use our new list
							b.setAction(Actions.BL_UPDATE);
							ServerSender.outQ.add(b);
							jdRemoveBuddy.dispose();
						}
					}
				});
				
				
 				
			}
		});
		
		// block a user from contacting us
		blockBuddy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				jdBlockBuddy = new JDialog();
				JPanel jp = new JPanel();
				JLabel jl = new JLabel("Username");
				addBuddyJTF = new JTextField(10);
				JButton add = new JButton("Block");
				add.setMnemonic('B');
				
				jp.add(jl);
				jp.add(addBuddyJTF);
				jp.add(add);
				jdBlockBuddy.add(jp);
				
				jdBlockBuddy.pack();
				jdBlockBuddy.setTitle("Block User");
				
				jdBlockBuddy.setLocationRelativeTo(null);
				jdBlockBuddy.setVisible(true);
				
				add.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						if (!(addBuddyJTF.getText().equals(""))) {
							// request that the user block this person's attempts to reach us
							BlockMsg b = new BlockMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, addBuddyJTF.getText());
							b.setAction(Actions.BLOCK);
							ServerSender.outQ.add(b);
							jdBlockBuddy.dispose();
						}
					}
				});
			}
		});
		
		// allow this person to contact us again
		unblockBuddy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				jdUnblockBuddy = new JDialog();
				JPanel jp = new JPanel();
				JLabel jl = new JLabel("Username");
				addBuddyJTF = new JTextField(10);
				JButton add = new JButton("Unblock");
				add.setMnemonic('U');
				
				jp.add(jl);
				jp.add(addBuddyJTF);
				jp.add(add);
				jdUnblockBuddy.add(jp);
				
				jdUnblockBuddy.pack();
				jdUnblockBuddy.setTitle("Unblock User");
				
				jdUnblockBuddy.setLocationRelativeTo(null);
				jdUnblockBuddy.setVisible(true);
				
				add.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						if (!(addBuddyJTF.getText().equals(""))) {
							BlockMsg b = new BlockMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, addBuddyJTF.getText());
							//request that the server allow their communications through
							b.setAction(Actions.UNBLOCK);
							ServerSender.outQ.add(b);
							jdUnblockBuddy.dispose();
						}
					}
				});
			}
		});
		
		// so i havent implemented admins, or closed chats yet.
		// and probably WONT.
		// creates a new chat room
		newChat.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				//////
				// GUI SETUP
				//////
				newChatDialog = new JDialog();
				newChatDialog.setTitle("Create New Chat");
				
				JPanel titlePanel = new JPanel();
				JLabel titleLabel = new JLabel("Title");
				title = new JTextField(20);
				titlePanel.add(titleLabel);
				titlePanel.add(title);
				newChatDialog.add(titlePanel, BorderLayout.NORTH);
				
				JPanel buttonPanel = new JPanel();
				JButton create = new JButton("Create");
				JButton cancel = new JButton("Cancel");
				create.setMnemonic('C');
				cancel.setMnemonic('a');
				buttonPanel.add(create);
				buttonPanel.add(cancel);
				newChatDialog.add(buttonPanel, BorderLayout.SOUTH);
				
				JPanel usersPanel = new JPanel(new BorderLayout());
				newChatDialog.add(usersPanel, BorderLayout.CENTER);
				
				currentUsersData = new Vector<String>();
				currentUsers = new JList(currentUsersData);
				JScrollPane currentUsersJSP = new JScrollPane(currentUsers);
				TitledBorder currentUsersTitle;
				currentUsersTitle = BorderFactory.createTitledBorder("Members to add to chat");
				currentUsersJSP.setBorder(currentUsersTitle);
				usersPanel.add(currentUsersJSP, BorderLayout.WEST);
				
				JPanel moveButtonsPanel = new JPanel();
				moveButtonsPanel.setLayout(new BoxLayout(moveButtonsPanel, BoxLayout.Y_AXIS));
				JButton moveLeft = new JButton("<--");
				JButton moveRight = new JButton("-->");
				moveButtonsPanel.add(Box.createVerticalGlue());
				moveButtonsPanel.add(moveLeft);
				moveButtonsPanel.add(Box.createVerticalGlue());
				moveButtonsPanel.add(moveRight);
				moveButtonsPanel.add(Box.createVerticalGlue());
				usersPanel.add(moveButtonsPanel, BorderLayout.CENTER);
				
				JPanel userSelectionPanel = new JPanel();
				userSelectionPanel.setLayout(new BoxLayout(userSelectionPanel, BoxLayout.Y_AXIS));
				buddies = new JList(TTClient.blData);
				JScrollPane buddiesJSP = new JScrollPane(buddies);
				TitledBorder buddiesJSPTitle;
				buddiesJSPTitle = BorderFactory.createTitledBorder("Buddy List");
				buddiesJSP.setBorder(buddiesJSPTitle);
				userSelectionPanel.add(buddiesJSP);
				userSelectionPanel.add(Box.createRigidArea(new Dimension(0, 10)));
				additionalUsers = new JTextField(10);
				additionalUsers.setMaximumSize(new Dimension(150,25));
				TitledBorder additionalUsersTitle;
				additionalUsersTitle = BorderFactory.createTitledBorder("Additional user(s)");
				additionalUsers.setBorder(additionalUsersTitle);
				userSelectionPanel.add(additionalUsers);
				usersPanel.add(userSelectionPanel, BorderLayout.EAST);
	
				newChatDialog.setSize(500,500);
				newChatDialog.setLocationRelativeTo(null);
				newChatDialog.setVisible(true);
				
				/////////
				/// Functional stuff
				////////
				
				moveLeft.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						// So, we want to grab all the users on the selected list, and the users in the box.
						// we dont want duplicates, so we create an arraylist, then dump it into a set, which doesnt allow dups
						ArrayList<String> usersToAdd = new ArrayList<String>();

						Object[] fromBL = buddies.getSelectedValues();
						for (int i = 0; i < fromBL.length; i++) {
							String s = fromBL[i].toString();
							usersToAdd.add(s);
						}
						
						// next we get the string of users that they want to add from the box
						String s = additionalUsers.getText();
						String sspace[];
						String sboth[];
						// so, we let them split it either on commas or spaces, or both...
						if (!s.equals("")) {
							if (s.contains(" ")) {
								// splitting on spaces first
								sspace = s.split(" ");
								for (String st: sspace) {
									// then on commas
									if (st.contains(",")) {
										sboth = st.split(",");
										// finally we have a single user
										for (String sts: sboth) usersToAdd.add(sts);
									}
									// finally we have a single user
									else usersToAdd.add(st);
								}
							}
							else {
								// no spaces?
								// splitting on commas alone...
								sboth = s.split(",");
								for (String st: sboth) usersToAdd.add(st);
							}
						}
						
						// now, get rid of duplicates in THIS set!
						Set<String> dupRemovedSet = new HashSet<String>(usersToAdd);
						// add them to the currentlist...
						currentUsersData.addAll(usersToAdd);
						// make sure there are no duplicates in THAT set 
						dupRemovedSet = new HashSet<String>(currentUsersData);
						currentUsersData.clear();
						currentUsersData.addAll(dupRemovedSet);
						Collections.sort(currentUsersData);
						// repaint the lists, set things to "" etc
						currentUsers.setListData(currentUsersData);
						currentUsers.repaint();
						additionalUsers.setText("");
						buddies.setSelectedIndex(-1);
					}
				});
				
				// this lets us remove users from the proposed memberlist
				moveRight.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						Object[] selected = currentUsers.getSelectedValues();
						for (int i = 0; i < selected.length; i++) {
							String s = selected[i].toString();
							currentUsersData.remove(s);
						}
						Collections.sort(currentUsersData);
						currentUsers.setListData(currentUsersData);
						currentUsers.repaint();
					}
				});
				
				// booo, they dont want to chat? :(
				cancel.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						newChatDialog.dispose();
					}
				});
				
				// actually creates the chat
				create.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						// add ourselves in there if they didnt specify it!
						if (!currentUsersData.contains(TTClient.name)) currentUsersData.add(TTClient.name);
						ArrayList<String> as = new ArrayList<String>(currentUsersData);
						
						// require a title
						if (title.getText().equals("")) {
							JOptionPane.showMessageDialog(null, "Must specify a title for this chat room!", "Title needed!", JOptionPane.ERROR_MESSAGE);
							return;
						}
						// construct the creation message
						ChatMsg c = new ChatMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, (new ArrayList<String>()), as, title.getText(), false);

						c.setAction(Actions.NEW_CHAT);
						ServerSender.outQ.add((ClientMsg)c);
						newChatDialog.dispose();
					}
				});
			}
		});
		
		// join an existing chat
		joinChat.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				joinChatDialog = new JDialog();
				JButton join = new JButton("Join");
				join.setMnemonic('J');
				title = new JTextField(15);
				JLabel tLabel = new JLabel("Chat Title");
				JPanel jp = new JPanel();
				jp.add(tLabel);
				jp.add(title);
				jp.add(join);
				joinChatDialog.add(jp);
				joinChatDialog.setTitle("Join Chat");
				joinChatDialog.pack();
				joinChatDialog.setLocationRelativeTo(null);
				joinChatDialog.setVisible(true);
				
				join.addActionListener( new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						ChatMsg c = new ChatMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, null, null, title.getText(), false);
						c.setTitle(title.getText());
						// try to join
						c.setAction(Actions.JOIN_CHAT);
						ServerSender.outQ.add((ClientMsg)c);
						joinChatDialog.dispose();
					}
				});
				
			}
		});
		
		// view someone's profile (even our own)
		viewProfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				jdViewProfile = new JDialog();
				JButton view = new JButton("View");
				view.setMnemonic('V');
				title = new JTextField(10);
				JLabel tLabel = new JLabel("Username");
				JPanel jp = new JPanel();
				jp.add(tLabel);
				jp.add(title);
				jp.add(view);
				jdViewProfile.add(jp);
				jdViewProfile.setTitle("View Profile");
				jdViewProfile.pack();
				jdViewProfile.setLocationRelativeTo(null);
				jdViewProfile.setVisible(true);
				
				view.addActionListener( new ActionListener() {
					public void actionPerformed(ActionEvent ae) {
						if (!(title.getText().equals(""))) {
							ProfileMsg pm = new ProfileMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, title.getText());
							pm.setWantsProfile(title.getText());
							// send off the request.
							pm.setAction(Actions.PROFILE_REQUEST);
							ServerSender.outQ.add(pm);
							jdViewProfile.dispose();
						}
					}
				});
				
			}
		});
		
		// request to edit our profile
		editProfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				ProfileMsg pm = new ProfileMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, TTClient.name);
				pm.setWantsProfile(TTClient.name);	// we need to pull down our own profile first .. .so we dont have to start all over again from scratch each time
				pm.setAction(Actions.PROFILE_REQUEST);
				ServerSender.outQ.add(pm);
				TTClient.updatingProfile = true;	// set this variable so the MsgParser class knows what we were trying to do
			}
		});

		/// this is the double click listener on the buddylist
		bl.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent me)
			{
				if(me.getClickCount() == 2)
				{
					// create a new pmmsg with the selected user as the target 
					PMMsg pm = new PMMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key, bl.getSelectedValue().toString(), null, false);
					// voodoo code. some values were getting nulled out somehow.... REALLY make sure they're set... 
					pm.setName(TTClient.name);
					pm.setWantsUser(bl.getSelectedValue().toString());
					String s = bl.getSelectedValue().toString();
					pm.setWantsUser(s);
					pm.setAction(Actions.PM_USER);
					ServerSender.outQ.add(pm);
				}
			}
		});
		
	}
	
	public void run() {
		while (true) {
			// infinitely loop, checking to see if we need to update our buddylist
			if (TTClient.updateBLNeeded) {
				bl.setListData(TTClient.blData);
				jf.repaint();
				TTClient.updateBLNeeded = false;
			}
		}
	}
	
	// just sends the logout message to the server, letting them know we're leaving
	private void logout() {
		ClientMsg c = new ClientMsg(TTClient.ip, TTClient.name, TTClient.pwd, TTClient.key);
		c.setAction(Actions.LOGOUT);
		ServerSender.outQ.add(c);
		try {
			// we have to sleep here. the server tends to not close connections quickly.
			Thread.sleep(1500);
		}
		catch(Exception e) {}
	}
	
	// as of right now this class doesn't do anything, because JDIC is such an old library.... Don't know if we can actually fix this.
	public void updateTrayIcon()
	{
		/*
		// MouseListeners unfortunately are not in this outdated library....
		// and the actionlistener does us virtually no good...
		TTClient.trayIcon.addActionListener(new ActionListener() {
		//TTClient.trayIcon.addMouseListener(new MouseAdapter()
		
			//public void mouseClicked(MouseEvent me)
			public void actionPerformed(ActionEvent ae) {
			
				System.out.println(ae.getActionCommand());
			
//				if(me.getClickCount() == 2)
//				{
//					try
//					{
//						if(jf.isVisible())
//						{
//							jf.setVisible(false);
//						}
//						else
//						{
//							jf.setVisible(true);
//						}
//					}
//					catch(NullPointerException npe)
//					{
//						System.out.println("BL not yet created");
//					}
//				}
			}
		}); */
	}
}

/**
 * This is our custom JList cell renderer for the TigerTalk Buddylist
 * @author Andrew Hayworth
 *
 */
class BLRenderer extends DefaultListCellRenderer {
	private HashMap <String, Integer> status;  // local copy of the status table
	public Component getListCellRendererComponent(JList list, 
            Object value,
            int index, 
            boolean isSelected,
            boolean cellHasFocus) {

		super.getListCellRendererComponent(list, 
                value, 
                index, 
                isSelected, 
                cellHasFocus);
		
		status = TTClient.blDataStatus;
		// set them to red if offline, green if online
		if (!status.containsKey(value.toString()) || status.get(value.toString()) == 0) {
			setBackground(Color.RED);
		}
		else setBackground(Color.GREEN);
		
		return this;
	}
}
